package ute.mvc.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ute.mvc.dao.UserDAO;
import ute.mvc.model.OpenCourse;
import ute.mvc.model.User;
import ute.mvc.util.PasswordUtil;

@Service("userService")
public class UserServiceImp implements UserService {
	@Autowired
	UserDAO userDAO;

	public User getUserByEmail(String email) {
		return userDAO.getUserByEmail(email);
	}

	public List<User> getAllUser() {
		return userDAO.getAllUser();
	}

	public List<User> findUserByEmail(String email) {
		return userDAO.findUserByEmail(email);
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void addUser(User user) {
		user.setPassword(PasswordUtil.hashPassword(user.getPassword()));
		userDAO.addUser(user);
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void updateUser(User user) {

		if ("".equals(user.getPassword())) {
			// String oldPassword = userDAO.getUserPassword(user.getUserId());
			String oldPassword = userDAO.getUserById(user.getUserId())
					.getPassword();
			user.setPassword(oldPassword);
		} else {
			user.setPassword(PasswordUtil.hashPassword(user.getPassword()));
		}
		userDAO.updateUser(user);
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void deleteUser(User user) {
		userDAO.deleteUser(user);
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public User getUserById(int id) {
		return userDAO.getUserById(id);
	}

	public String getUserPassword(int id) {
		return userDAO.getUserPassword(id);
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void updatePassword(User user) {
		// TODO Auto-generated method stub
		user.setPassword(PasswordUtil.hashPassword(user.getPassword()));
		userDAO.updateUser(user);

	}

	public List<OpenCourse> getListOpenCourseWithLecturerId(int lecturerId) {
		// TODO Auto-generated method stub
		return userDAO.getListOpenCourseWithLecturerId(lecturerId);
	}

	public boolean deleteUsers(String[] userIds) {
		try {
			for(String id : userIds) {
				userDAO.deleteUser(userDAO.getUserById(Integer.parseInt(id)));
			}
			return true;
		} catch (Exception ex) {
			return false;
		}
	}
}
